#!coding=utf-8
from django.db.models.loading import get_model

#自动装载表单  request：请求体  ,appname：应用名称,modelname:模块类名
def auto_wear(request,obj,appname,modelname):
    fields = getmodelfield(appname,modelname) 
    for key in fields:
        type = fields[key]  
        wear(request,key,obj,type)
#装载属性 attr :属性名，type属性类型
def wear(request,attr,object,type):
    if attr in request.POST or request.FILES.get(attr, None):
        if type == "CharField":
            str = ""
            for a in request.POST.getlist(attr):
                str+= a
            setattr(object, attr, str)
        elif type == "IntegerField":
            if request.POST[attr]:
                setattr(object, attr, int(request.POST[attr]))
            else:
                setattr(object, attr, 0) 
        elif type == "FileField":
            if request.FILES.get(attr, None):
                setattr(object, attr, request.FILES.get(attr, None))
#获取model的属性字典        
def getmodelfield(appname,modelname):
    modelobj = get_model(appname,modelname)
    fielddic={}
    for field in modelobj._meta.fields:
        fielddic[field.name] = type(field).__name__
    return fielddic



#批量装载
def auto_wear_list(request,obj,appname,modelname):
    field_list = []
    names = []
    objs = []
    fields = getmodelfield(appname,modelname) 
    for key in fields:
        type = fields[key]
        wear_list(request,key,obj,type,field_list,names)
    if field_list:
        list1 = field_list[0]
        for li in xrange(len(list1)):
            cobj = obj()
            k = 0
            for key in field_list:
                setattr(cobj, names[k], key[li])
                k = k + 1
            objs.append(cobj) 
    return objs            
        
#装载属性 attr :属性名，type属性类型
def wear_list(request,attr,object,type,field_list,names):
    if attr in request.POST:
        if type == "CharField":
            field_list.append(request.POST.getlist(attr))
        elif type == "IntegerField":
            bak = []
            for key in request.POST.getlist(attr):
                if key:
                    bak.append(int(key))
                else:
                    bak.append(int(0))    
            field_list.append(bak)
        names.append(attr)    
                
                            